import Dialog from '@vant/weapp/dialog/dialog';
var App = getApp();

Component({
  data: {
    address: {},
    freight: 0,
    totalAmount: 0,
    signlePrice: {},
    phone: '',
    remark: '',
    orderId: '',
    userInfo: {},
    payType: '',
    order: {},
    isclick:true
  },
  properties: {
    goType: {
      type: Number,
      value: 1
    },
    goodsList: {
      type: Array,
      value: []
    },
    show: {
      type: Boolean,
      value: false
    },
  },
  attached: function () {
    const _this = this
    App.globalData.userModel.getDefaultAdd().then(json => {
      _this.setData({
        address: json.data,
        cids: wx.getStorageSync('attr')
      })
      _this.getFreight()
    })
    App.globalData.userModel.userInfo().then(res => {
      _this.setData({ userInfo: res.data,isfirst:1})
    })
  }, // 此处attached的声明会被lifetimes字段中的声明覆盖

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      const _this = this
      if (App.globalData.address.id) {
        _this.setData({address: App.globalData.address})
        _this.getFreight()
      }
    },
    hide: function () {},
    resize: function () {},
  },

  methods: {
    previewImage(e) {
      var urls = []
      this.data.goodsList.forEach(val => {
        urls.push(val.domain_url)
      });
      wx.previewImage({
        current: e.currentTarget.dataset.url,
        urls: urls
      })
    },
    getFreight() {
      const _this = this
      App.globalData.serviceModel.getFreight({
        data: {
          user_address_id: _this.data.address.id
        }
      }).then(json => {
        _this.setData({
          freight: json.data
        })
        App.globalData.serviceModel.getOrderDetailPrices({
          data: {
            goodList: JSON.stringify(_this.properties.goodsList),
            cids: _this.data.cids,
          }
        }).then(json => {
          if (json.other==true){
            wx.showToast({
              title:"请手动输入正确页数",
              icon:"none"
            })
          }
          _this.setData({ goodsList: json.data})
          _this.updateTotal()
        })
      })
    },
    changeGoType: function (res) {
      let _this = this;
      let goType = res.currentTarget.dataset.gotype;
      _this.setData({
        goType: goType
      })
      _this.updateTotal()
    },
    deleteGoods: function (res) {
      let _this = this;
      let index = res.currentTarget.dataset.index;
      let goodsList = _this.properties.goodsList;
      Dialog.confirm({
        title: '确认删除',
        message: '确认删除商品？'
      }).then(() => {
        goodsList.splice(index, 1);
        _this.setData({
          goodsList: goodsList
        })
        _this.getOrderDetailPrices()
      });
    },
    onSubmit: function (res) {
      if(!this.data.isclick) return;
      const _this = this
      var address_id = 0
      if (this.data.goType == 1) {
        if (!this.data.address || !this.data.address.id) {
          Dialog.alert({
            title: '请选择收货地址'
          }).then(() => {})
          return
        } else {
          address_id = this.data.address.id
        }
      } else if (this.data.goType == 2) {
        if (!this.data.phone) {
          Dialog.alert({
            title: '请填写预留电话'
          }).then(() => { })
          return
        }
      }

      _this.setData({isclick:false})
      var imgList = this.properties.goodsList.map(element => {
        return {
          num: element.num ? element.num : 1,
          url: JSON.parse(element.pic)[0]
        }
      })

      if (this.data.isfirst==1 ){
        Dialog.alert({
          title: "当前门店" + App.globalData.curStore.company_name,
          message: App.globalData.curStore.contact_addr
        })
        _this.setData({isfirst:0})
      }
      App.globalData.serviceModel.createOrder({
        data: {
          user_address_id: address_id,
          obj: JSON.stringify(imgList),
          cids: _this.data.cids.split(','),
          phone: _this.data.phone,
          remark: _this.data.remark
        }
      }).then(json => {
        _this.setData({isfirst:1})
        if (json.other!=''){
          wx.showToast({
            title: json.other,
            icon:"none"
          });
        }else{
          App.globalData.imageList = [] //清空选择的图片
          _this.setData({
            show: true,
            order: json.data
          })
        }
        
      })
    },
    onChangeRemark(event) {
      this.setData({
        remark: event.detail
      })
    },
    onChangePhone(event) {
      this.setData({
        phone: event.detail
      })
    },
    closePay: function (res) {
      this.setData({
        show: false
      })
      wx.redirectTo({
        url: '/pages/person/order/detail/detail?id=' + this.data.order.id,
      });
    },

    payment(event) {
      var _this = this
      if (!this.data.payType) {
        wx.showToast({
          title: '请选择支付方式',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false,
        });
        return
      }
      App.globalData.serviceModel.payment({
        data: {
          id: _this.data.order.id,
          pay_type: _this.data.payType
        }
      }).then(json => {
        _this.setData({
          show: false
        })
        if (_this.data.payType == 1) {
          wx.requestPayment({
            timeStamp: json.data.timeStamp,
            nonceStr: json.data.nonceStr,
            package: json.data.package,
            signType: json.data.signType,
            paySign: json.data.paySign,
            complete(res) {
              wx.redirectTo({
                url: '/pages/person/order/detail/detail?id=' + _this.data.order.id,
              });
            }
          })

        } else {
          wx.redirectTo({
            url: '/pages/person/order/detail/detail?id=' + _this.data.order.id,
          });
        }
      })

    },
    onStepBlur(event) {
      this.data.goodsList.forEach(element => {
        if (event.currentTarget.dataset.id == element.id) {
          element.num = event.detail.value
        }
      });
      this.properties.goodsList = this.data.goodsList
      this.getOrderDetailPrices()
    },
    onStepPlus(event) {
      this.data.goodsList.forEach(element => {
        if (event.currentTarget.dataset.id == element.id) {
          element.num = element.num + 1
        }
      });
      this.properties.goodsList = this.data.goodsList
      this.getOrderDetailPrices()
    },

    onStepMin(event) {
      this.data.goodsList.forEach(element => {
        if (event.currentTarget.dataset.id == element.id) {
          if (element.num > 1)
            element.num = element.num - 1
        }
      });
      this.properties.goodsList = this.data.goodsList
      this.getOrderDetailPrices()
    },

    updateTotal() {
      var totalAmount = 0
      this.data.goodsList.forEach(element => {
        totalAmount += Number(element.goods_price)
      });
      if (this.data.goType == 1)
        totalAmount += parseFloat(this.data.freight)
      this.setData({ totalAmount: totalAmount.toFixed(1)})
    },

    onChange(event) {
      this.setData({
        radio: event.detail
      });
    },

    onClick(event) {
      const {
        name
      } = event.currentTarget.dataset;
      this.setData({
        payType: name
      });
    },

    selectAddr: function () {
      wx.navigateTo({
        url: '/pages/index/devphoto/selectaddr/selectaddr',
      });
    },

    getOrderDetailPrices() {
      const _this = this
      App.globalData.serviceModel.getOrderDetailPrices({
        data: {
          goodList: JSON.stringify(_this.properties.goodsList),
          cids: _this.data.cids,
        }
      }).then(json => {
        this.setData({
          goodsList: json.data
        })
        _this.updateTotal()
      })
    }


  }
})